package com.zhiche.lisa.lspm.service.fleet.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.lspm.dao.mapper.fleet.FleetAdminMapper;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.driver.Driver;
import com.zhiche.lisa.lspm.dao.model.driver.bo.DriverCheckinLineBO;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetAdmin;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBind;
import com.zhiche.lisa.lspm.dao.model.lsp.LspInfo;
import com.zhiche.lisa.lspm.dao.model.sys.User;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dto.DriverCheckinDTO;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.driver.IDriverCheckinService;
import com.zhiche.lisa.lspm.service.driver.IDriverService;
import com.zhiche.lisa.lspm.service.fleet.FleetAdminService;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindService;
import com.zhiche.lisa.lspm.service.fleet.IFleetService;
import com.zhiche.lisa.lspm.service.lsp.LspInfoService;
import com.zhiche.lisa.lspm.service.sys.IUserService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.Account;
import com.zhiche.lisa.lspm.vo.common.AccountVO;
import com.zhiche.lisa.lspm.vo.driver.DriverCheckinLineVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetAdminVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetTypeVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 车队管理员表 服务实现类
 * </p>
 *
 * @author hongbo
 * @since 2018-10-29
 */
@Service
public class FleetAdminServiceImpl extends ServiceImpl<FleetAdminMapper, FleetAdmin> implements FleetAdminService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FleetAdminServiceImpl.class);

    @Autowired
    private IDriverService driverService;

    @Autowired
    private IDriverCheckinService driverCheckinService;

    @Autowired
    private UaaUtil uaaUtil;

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFleetBindService fleetBindService;

    @Autowired
    private IFleetService fleetService;

    @Autowired
    private ICarrierInfoService carrierInfoService;

    @Autowired
    private TrailerInfoService trailerInfoService;

    @Autowired
    private LspInfoService lspInfoService;

    @Value("${uaa.accountGetAccountuRrl}")
    private String accountGetAccountuRrl;

    @Value("${uaa.socketTimeout}")
    private Integer socketTimeout;

    @Value("${integration.url}")
    private String integrationUrl;

    @Override
    @Transactional
    public void addFleetAdmin(FleetAdmin fleetAdmin, String authorization) {
        if (Objects.isNull(fleetAdmin.getFleetId())) throw new BaseException("车队不能为空");
        if (StringUtils.isEmpty(fleetAdmin.getName())) throw new BaseException("姓名不能为空");
        if (StringUtils.isEmpty(fleetAdmin.getMobile())) throw new BaseException("手机号不能为空");
        Fleet fleet = fleetService.selectById(fleetAdmin.getFleetId());
        fleetAdmin.setTenantId(fleet.getTenantId());

        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        List<NameValuePair> pramsNamePairs = Lists.newArrayList();
        pramsNamePairs.add(new BasicNameValuePair("identifier", fleetAdmin.getMobile()));
        String isOpen = HttpClientUtil.get(accountGetAccountuRrl, headNamePairs, pramsNamePairs, socketTimeout);
        JSONObject jsonObject = JSONObject.parseObject(isOpen);
        if (Integer.valueOf(jsonObject.get("code").toString()) == 0) {
            fleetAdmin.setAccountId(jsonObject.getJSONObject("data").getLong("id"));
            fleetAdmin.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        }else {
            RestfulResponse<Account> signup = uaaUtil.signup("", fleetAdmin.getMobile(), fleetAdmin.getPassword(), authorization, fleet.getTenantId());
            if (CommonEnum.SUCCESS.getCode().equals(signup.getCode())) {
                fleetAdmin.setAccountId(Long.valueOf(signup.getData().getId()));
                fleetAdmin.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
            } else {
                throw new BaseException(signup.getMessage());
            }
        }

        User user=new User();
        user.setName(fleetAdmin.getName());
        user.setMobile(fleetAdmin.getMobile());
        user.setAccountId(String.valueOf(fleetAdmin.getAccountId()));
        user.setDepartment("fleet");
        user.setLspId(fleetAdmin.getLspId());
        user.setCreateUser(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        user.setModifiedUser(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        userService.addUser(user);
        Wrapper<FleetAdmin> fleetAdminWrapper=new EntityWrapper<>();
        fleetAdminWrapper.eq("mobile", fleetAdmin.getMobile())
                .eq("fleet_id", fleetAdmin.getFleetId());
        List<FleetAdmin> fleetAdmins = this.selectList(fleetAdminWrapper);
        if (CollectionUtils.isEmpty(fleetAdmins)){
            this.insert(fleetAdmin);
        }

    }

    @Override
    public Driver queryAccountByPhone(String phone) {
        if (StringUtils.isEmpty(phone)) throw new BaseException("手机号不能为空");
        Wrapper<Driver> driverWrapper=new EntityWrapper<>();
        driverWrapper.eq("mobile",phone);
        Driver driver = driverService.selectOne(driverWrapper);
        if (Objects.isNull(driver)){
            throw new BaseException("未查到信息.请先注册");
        }
        return driver;
    }

    @Override
    public Page<FleetAdminVO> queryFleetAdminList(Page<FleetAdminVO> page, String authorization) {
          Wrapper<FleetAdminVO> fleetAdminWrapper= new EntityWrapper<>();
        // 手机号
        if (page.getCondition() != null){
            if (!StringUtils.isEmpty(String.valueOf(page.getCondition().get("mobile"))))
                fleetAdminWrapper.like("lfd.mobile", page.getCondition().get("mobile").toString().trim());
            if (!StringUtils.isEmpty(String.valueOf(page.getCondition().get("fleetName"))))
                fleetAdminWrapper.like("lf.fleet_name", page.getCondition().get("fleetName").toString().trim());
        }
        List<FleetAdminVO> fleetAdminVOS = baseMapper.queryFleetAdminList(page, fleetAdminWrapper);
        for (FleetAdminVO fleetAdminVO : fleetAdminVOS) {
            AccountVO account = uaaUtil.getAccountById(fleetAdminVO.getCreator(), authorization);
            if (Objects.nonNull(account)) {
                fleetAdminVO.setCreator(account.getCorpName());
            }
            List<FleetTypeVO> allFleetTypeByType = mdmUtil.getAllFleetTypeByType();
            for (FleetTypeVO fleetTypeVO : allFleetTypeByType) {
                if (Objects.nonNull(fleetAdminVO.getFleetTypeId())&&fleetAdminVO.getFleetTypeId().equals(fleetTypeVO.getId())){
                    fleetAdminVO.setFleetTypeName(fleetTypeVO.getValue());
                }
            }
        }

        page.setRecords(fleetAdminVOS);
        return page;
    }

    @Override
    public void fleetCheckIn(DriverCheckinDTO dto, String token) {
        if (Objects.isNull(dto.getFleetId()))throw new BaseException("车队id不能为空!");
        if (Objects.isNull(dto.getCarrierId()))throw new BaseException("车辆id不能为空!");
        //查询承运商是否被禁用
        LspInfo lspInfo = lspInfoService.selectLspInfo(dto.getLspId());
        if (lspInfo.getStatus()==0){
            throw new BaseException("承运商已被禁用");
        }
        //查询车队是否被禁用
        Fleet fleet = fleetService.selectById(dto.getFleetId());
        if (!Objects.isNull(fleet) && fleet.getIsDelete() == 1) {
            throw new BaseException("车队已被禁用");
        }
        Wrapper<FleetBind> fleetBindWrapper=new EntityWrapper<>();
        fleetBindWrapper.eq("resource_id",dto.getCarrierId());
        fleetBindWrapper.eq("resource_type",TableStatusEnum.STATUS_01.getCode());
        FleetBind fleetBind = fleetBindService.selectOne(fleetBindWrapper);
        if (fleetBind.getFleetId().intValue()!=dto.getFleetId().intValue()) throw new BaseException("该车队没有该车!");
        driverCheckinService.insertNewCheckIn(dto,token);
    }


    @Override
    public Page<DriverCheckinLineVO> fleetCheckinLine(Page<DriverCheckinLineBO> page) {
        if (StringUtils.isEmpty(page.getCondition().get("fleetId").toString())) throw new BaseException("不是车队管理员,不能进行此操作!");
        page.setOrderByField("gmtCheckin");
        page.setAsc(false);
        List<DriverCheckinLineVO> list = baseMapper.fleetCheckinLine(page,
                buildCondition(page.getCondition()));
        Page<DriverCheckinLineVO> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        for (DriverCheckinLineVO driverCheckinLineVO : list) {
            CarrierInfo carrierInfo = carrierInfoService.selectById(driverCheckinLineVO.getCarrierId());
            if (Objects.nonNull(carrierInfo)) {
                driverCheckinLineVO.setCarrierPlate(carrierInfo.getPlate());
            }
            TrailerInfo trailerInfo = trailerInfoService.selectById(driverCheckinLineVO.getTrailerId());
            if (Objects.nonNull(trailerInfo)) {
                driverCheckinLineVO.setTrailerPlate(trailerInfo.getPlate());
            }

        }
        pageVo.setRecords(list);
        return pageVo;
    }

    @Override
    public String selectFleetAdminByName(String name) {
        Wrapper<FleetAdmin> ew = new EntityWrapper<>();
        String mobile="";
        if (name!=null && !"".equals(name)){
            ew.like("name", name);
              //mobile = baseMapper.selectFleetAdminByName(ew);
            List<FleetAdmin> fleetAdmins = baseMapper.selectList(ew);
            if(CollectionUtils.isEmpty(fleetAdmins)){
                return mobile;
            }else {
                mobile=fleetAdmins.get(0).getMobile();
                return mobile;
            }
        }
        return mobile;
    }

    //启运地、目的地、承运商名称、司机手机、牵引车牌、挂车车牌、报班时间（between）、计划装车时间
    //构建认证承运商查询条件
    private EntityWrapper<DriverCheckinLineBO> buildCondition(Map<String, Object> condition) {
        EntityWrapper<DriverCheckinLineBO> ew = new EntityWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (!Objects.equals(condition, null)) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!StringUtils.isEmpty(entry.getValue().toString())) {
                    if (entry.getKey().equals("departRegion")) {
                        ew.like("departRegion", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("destRegion")) {
                        ew.like("destRegion", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("driverMobile")) {
                        ew.like("driverMobile", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("lspName")) {
                        ew.eq("lspName", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("lspId")) {
                        ew.eq("lspId", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("carrierPlate")) {
                        EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
                        carrierInfoEntityWrapper.like("plate", entry.getValue().toString());
                        List<CarrierInfo> carrierInfoList = carrierInfoService.selectList(carrierInfoEntityWrapper);
                        if (CollectionUtils.isNotEmpty(carrierInfoList)) {
                            List<Long> ids = carrierInfoList.stream().map(CarrierInfo::getId).collect(Collectors.toList());
                            ew.in("carrierId", ids);
                        }
                    }
                    if (entry.getKey().equals("trailerPlate")) {
                        EntityWrapper<TrailerInfo> trailerInfoEntityWrapper = new EntityWrapper<>();
                        trailerInfoEntityWrapper.like("plate", entry.getValue().toString());
                        List<TrailerInfo> trailerInfoList = trailerInfoService.selectList(trailerInfoEntityWrapper);
                        if (CollectionUtils.isNotEmpty(trailerInfoList)) {
                            List<Long> ids = trailerInfoList.stream().map(TrailerInfo::getId).collect(Collectors.toList());
                            ew.in("trailerId", ids);
                        }
                    }
                    if (entry.getKey().equals("gmtCheckinStart")) {
                        ew.ge("gmtCheckin", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("gmtCheckinEnd")) {
                        ew.le("gmtCheckin", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("gmtExpLoadStart")) {
                        ew.ge("gmtExpLoad", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("gmtExpLoadEnd")) {
                        ew.le("gmtExpLoad", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("checkinStatus")) {
                        ew.eq("checkinStatus", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("fleetId")){
                        String id = entry.getValue().toString();
                        String[] split = id.split(",");
                        List<String> strings = Arrays.asList(split);
                        ew.in("fleetId", strings);
                    }
                }
            }
        }
        return ew;
    }
}
